package com.tinyengine.it.service.db.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinyengine.it.mapper.DbDictionaryInfoMapper;
import com.tinyengine.it.model.entity.DbDictInfo;
import com.tinyengine.it.model.entity.DbDictionaryInfo;
import com.tinyengine.it.model.vo.DbDictInfoVo;
import com.tinyengine.it.model.vo.DbDictionaryInfoVo;
import com.tinyengine.it.service.db.DbDictInfoService;
import com.tinyengine.it.mapper.DbDictInfoMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【i_db_dict_info(数据字典条目信息)】的数据库操作Service实现
* @createDate 2025-03-17 16:18:30
*/
@Service
public class DbDictInfoServiceImpl extends ServiceImpl<DbDictInfoMapper, DbDictInfo>
    implements DbDictInfoService {

    @Resource
    private DbDictInfoMapper dbDictInfoMapper;
    @Resource
    private DbDictionaryInfoMapper dbDictionaryInfoMapper;

    @Override
    public DbDictInfoVo saveInfo(DbDictInfoVo dbDictInfoVo) {
        DbDictInfo dbDictInfo = BeanUtil.copyProperties(dbDictInfoVo, DbDictInfo.class);
        dbDictInfoMapper.insertOrUpdate(dbDictInfo);

        List<DbDictionaryInfo> dbDictionaryInfos = BeanUtil.copyToList(dbDictInfoVo.getDictionaryInfos(), DbDictionaryInfo.class);

        List<Integer> fields = dbDictionaryInfos.stream().filter(f -> ObjUtil.isNotNull(f.getId())).map(m -> m.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(fields) && fields.size() > 0) {
            dbDictionaryInfoMapper.delete(Wrappers.<DbDictionaryInfo>lambdaQuery().eq(DbDictionaryInfo::getParentId, dbDictInfo.getId()).notIn(DbDictionaryInfo::getId, fields));
        } else {
            dbDictionaryInfoMapper.delete(Wrappers.<DbDictionaryInfo>lambdaQuery().eq(DbDictionaryInfo::getParentId, dbDictInfo.getId()));
        }

        dbDictionaryInfos.forEach(e -> e.setParentId(dbDictInfo.getId()));
        dbDictionaryInfoMapper.insertOrUpdate(dbDictionaryInfos);

        DbDictInfoVo dbDictInfoVo1 = BeanUtil.copyProperties(dbDictInfo, DbDictInfoVo.class);
        List<DbDictionaryInfoVo> dbDictionaryInfoVos = BeanUtil.copyToList(dbDictionaryInfos, DbDictionaryInfoVo.class);
        dbDictInfoVo1.setDictionaryInfos(dbDictionaryInfoVos);

        return dbDictInfoVo1;
    }
}




